import defaults from 'lodash/defaults';
import React, { ChangeEvent, PureComponent } from 'react';
import { Field, Input } from '@grafana/ui';
import { QueryEditorProps } from '@grafana/data';
import { DataSource } from './DataSource';
import { defaultQuery, MyDataSourceOptions, MyQuery } from './types';

type Props = QueryEditorProps<DataSource, MyQuery, MyDataSourceOptions>;

export class QueryEditor extends PureComponent<Props> {

  constructor(props:Props) {
    super(props);
    console.warn('==props query=',this);
  }

  render() {
    const query = defaults(this.props.query, defaultQuery);
    const { queryText, constant, frequency } = query;

    return (
      <div className="gf-form">
        <Field label="Constant">
          <Input name="constant" value={constant || ''} onChange={this.onConstantChange} />
        </Field>
        <Field label="Query Text">
          <Input name="queryText" value={queryText || ''} onChange={this.onQueryTextChange} />
        </Field>

        <Field label="Frequency">
          <Input name="frequency" type="number" value={frequency} onChange={this.onFrequencyChange} />
        </Field>
      </div>
    );
  }

  onQueryTextChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { onChange, query } = this.props;
    onChange({ ...query, queryText: event.target.value });
  };

  onConstantChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { onChange, query, onRunQuery } = this.props;
    onChange({ ...query, constant: parseFloat(event.target.value) });
    // executes the query 更新查询后自动运行查询 onRunQuery
    onRunQuery();
  };

  onFrequencyChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { onChange, query, onRunQuery } = this.props;
    onChange({ ...query, frequency: parseFloat(event.target.value) });
    // 执行查询-query
    onRunQuery();
  };
}
